<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="活动标题" prop="activityTitle">
        <el-input
          v-model="queryParams.activityTitle"
          placeholder="请输入活动标题"
          clearable
          @keyup.enter="handleQuery"
          class="!w-200px"
        />
      </el-form-item>
      <el-form-item label="活动分类" prop="typeId">
        <el-tree-select
          v-model="queryParams.typeId"
          :data="activityTypeTree"
          :props="defaultProps"
          check-strictly
          default-expand-all
          placeholder="请选择活动分类"
          class="!w-200px"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-200px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="活动开始时间" prop="startTime" label-width="100px">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create', queryParams.categoryId)"
          v-hasPermi="['school:activity:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['school:activity:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button> -->
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- 子表的列表 内嵌模式-->
      <el-table-column type="expand">
        <template #default="scope">
          <el-tabs model-value="activityRecord">
            <el-tab-pane label="活动参与记录" name="activityRecord">
              <ActivityRecordOverview :activity-id="scope.row.id" />
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>

      <!-- <el-table-column label="编号" align="center" prop="id" /> -->
      <el-table-column
        label="活动标题"
        align="center"
        prop="activityTitle"
        :show-overflow-tooltip="false"
        width="120"
      />
      <el-table-column label="图标" align="center" prop="iconUrl">
        <template #default="{ row }">
          <el-image
            class="h-80px w-80px"
            lazy
            :src="row.iconUrl"
            :preview-src-list="[row.iconUrl]"
            preview-teleported
            fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column label="活动分类" align="center" prop="typeId">
        <template #default="scope">
          <template v-for="item in activityTypeList">
            <el-tag type="success" :key="item.id" v-if="item.id === scope.row.typeId">
              {{ item.name }}
            </el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        label="活动开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column
        label="活动结束时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter2"
        width="180px"
      />
      <el-table-column label="排序" align="center" prop="sort" sortable />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.COMMON_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="userName" />
      <el-table-column label="创建部门" align="center" prop="deptName" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
        sortable
      />
      <el-table-column label="操作" align="center" fixed="right" width="180">
        <template #default="scope">
          <el-button link type="success" @click="handleViewDetail(scope.row.id)"> 查看 </el-button>

          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.categoryId, scope.row.id)"
            v-hasPermi="['school:activity:update']"
          >
            编辑
          </el-button>

          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['school:activity:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ActivityForm ref="formRef" @success="getList" />
  <!-- 子表的列表  标准模式，子表在主表下面显示 -->
  <!-- <ContentWrap>
    <el-tabs model-value="activityRecord">
      <el-tab-pane label="活动参与概览" name="activityRecord">
        <ActivityRecordOverview :activity-id="currentRow?.id" />
      </el-tab-pane>
    </el-tabs>
  </ContentWrap> -->
</template>
<script setup lang="ts">
import { useRouter, useRoute } from 'vue-router'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import download from '@/utils/download'
import { ActivityApi, ActivityVO } from '@/api/school/activity'
import ActivityForm from './ActivityForm.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import ActivityRecordOverview from './components/ActivityRecordOverview.vue'
import { ActivityTypeApi, ActivityTypeVO } from '@/api/school/activitytype'
const router = useRouter()
const route = useRoute()
/** 活动 列表 */
defineOptions({ name: 'SchoolActivity' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ActivityVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  activityTitle: undefined,
  typeId: undefined,
  startTime: [],
  status: undefined,
  categoryId: 0
})

//查询分类的参数
const queryTypeParams = {
  categoryId: 0
}
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const activityTypeList = ref([] as ActivityTypeVO[]) // 活动分类列表
const activityTypeTree = ref() // 树形结构

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ActivityApi.getActivityPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, categoryId: number, id?: number) => {
  formRef.value.open(type, categoryId, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ActivityApi.deleteActivity(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ActivityApi.exportActivity(queryParams)
    download.excel(data, '活动.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 选中行操作 */
// const currentRow = ref({}) // 选中行
// const handleCurrentChange = (row) => {
//   currentRow.value = row
// }

const handleViewDetail = (id) => {
  console.log(id)
  router.push({ path: '/activity/detail', query: { id, backPath: route.path } })
}

// 路由到 categoryId 映射关系
const pathToAssetTypeMap = {
  '/activity/activity-teaching/activity-activity': 1, //教研活动
  '/activity/activity-mentorship/mentorship-activity': 2, //师徒结对活动
  '/activity/activity-research/research-activity': 3, //园本研修活动
  '/activity/activity-reception/reception-activity': 4, //接待活动
  '/activity/activity-union/union-activity': 5, //工会活动
  '/activity/activity-project/project-activity': 6, //课题活动
  '/activity/activity-curriculumBase/curriculumBase-activity': 7, //课程基地园活动
  '/activity/activity-transition/transition-activity': 8, //幼小衔接试点活动
  '/activity/activity-outdoorPlay/outdoorPlay-activity': 9, //安吉户外游戏试点活动
  '/activity/activity-awards/award-activity': 10 //评优评先活动
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(
  () => route.path,
  (path) => {
    console.log(path, '---path')

    // 匹配路径并赋值 resourceCode
    queryParams.categoryId = pathToAssetTypeMap[path] || 1
    queryTypeParams.categoryId = pathToAssetTypeMap[path] || 1
    console.log(queryParams.categoryId, '---categoryId')
  },
  {
    immediate: true //立即执行一次
  }
)

/** 获得活动分类树 */
const getActivityTypeTree = async () => {
  activityTypeTree.value = []
  const data = await ActivityTypeApi.getSimpleActivityTypeList(queryParams)
  if (!data?.length) {
    return
  }
  //转成树结构前，赋值给 activityTypeList，方便匹配显示分类名称
  activityTypeList.value = data
  activityTypeTree.value = handleTree(data, 'id', 'parentId')
}

onActivated(() => {
  //查询分类树
  getActivityTypeTree()
})
/** 初始化 **/
onMounted(async () => {
  getList()
  // 加载活动分类列表
  // activityTypeList.value = await ActivityTypeApi.getSimpleActivityTypeList(queryTypeParams)

  //查询分类树
  // await getActivityTypeTree()
})
</script>
